﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;


namespace IAS.Common
{
    public class NetHelper
    {
        static bool mailSent = false;
        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
            String token = (string)e.UserState;

            if (e.Cancelled)
            {
                Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            }
            else
            {
                Console.WriteLine("Message sent.");
            }
            mailSent = true;
        }

        public static bool SendMail(string head,string body,string mailto)
        {
            SmtpClient client = new SmtpClient("smtp.139.com");
            //var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.CurrentConfiguration;

            var mailName = ConfigurationManager.AppSettings["mailName"].ToString();
            var mailPw = ConfigurationManager.AppSettings["mailPw"].ToString();
            client.Credentials = new NetworkCredential(mailName, mailPw);
            MailAddress from = new MailAddress("15521030576@139.com", "WebAdmin", Encoding.UTF8);
            MailAddress to = new MailAddress(mailto);
            MailMessage message = new MailMessage(from, to);
            string subject = GetActiveCodeFmt(head, body);
            byte[] base64 = Encoding.UTF8.GetBytes(subject);
           // subject = Convert.ToBase64String(base64);
            message.Body = subject;            
            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.Subject = head?? "账户激活通知";
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            // Set the method that is called back when the send operation ends.
            //client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
            // The userState can be any object that allows your callback 
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            //client.SendAsync(message, mailto);
            
            client.Send(message);
            message.Dispose();

            return false;
        }

        private static string GetActiveCodeFmt(string name,string url)
        {            
            string str = System.IO.File.ReadAllText(@"ActiveCodeMainFmt.txt");
            str = str.Replace("{姓名}", name).Replace("{地址}",url) ;
            return str;
        }
    }
}
